﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using VAdvantage.Editor;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.Model;
using SilverlightDesktop.Controls;
using VAdvantage.Grids;
using VAdvantage.UIEvent;
using System.Text;
using System.Data.SqlClient;
using VAdvantage.DataBase;
using System.Data;
using System.Windows.Data;
using System.ComponentModel;
using System.Threading;
using VAdvantage.Framework;
using VAdvantage.Search;

namespace VAdvantage.Controls
{


    public partial class VTextBoxButton : UserControl, IControl, IContextMenuListener, IEditingControl
    {





        public event EventHandler VetoableChangeListener;

        #region Property

        public static readonly DependencyProperty TextValueProperty =
         DependencyProperty.Register("TextValue", typeof(int), typeof(VAdvantage.Controls.VTextBoxButton), new PropertyMetadata((o, e) =>
    {
        ((VTextBoxButton)o).SetTextValue((int)e.NewValue);

    }));


        public int TextValue
        {
            get
            {
                return ((int)GetValue(VTextBoxButton.TextValueProperty));
            }
            set
            {
                SetValue(VTextBoxButton.TextValueProperty, value);
            }
        }

        void SetTextValue(int newVal)
        {
            //TextValue = newVal;
            int? id = null;
            if (TextValue == 0)
            {
                id = null;
            }
            else
            {
                id = TextValue;
            }
            SetGetValue(id, false);


        }


        #endregion

        public VTextBoxButton()
        {
            InitializeComponent();
        }

        #region declaration
        // declare variables
        private string _columnName;
        private bool _mandatory = false;
        private bool _readOnly = false;
        private GridField _field;
        private int _displayType;
        private int _windowNum;
        private object _value;
        private Lookup _lookup;
        private MLocatorLookup _locator;
        private MLocationLookup _locationLookup;
        private MLocation _locationValue;
        ContextMenuStrip popupMenu;
        //ToolStripMenuItem zoomItem, refreshItem, preferenceItem, deleteItem;
        //ToolStripMenuItem newItem, updateItem;
        bool _textSetting = false;
        private Logging.VLogger log = null;
        bool _settingText = false;

        bool _focus = false;

        private Binding binding;
        private bool _updating = false;

        public bool TextSetting
        {
            get
            {
                return _textSetting;
            }
            set
            {
                _textSetting = value;
            }
        }

        public bool updating
        {
            get
            {
                return _updating;
            }
            set
            {
                _updating = value;
            }
        }

        private BackgroundWorker worker;


        #endregion

        /// <summary>
        /// Parameterized Constructor
        /// </summary>
        /// <param name="columnName">column name</param>
        /// <param name="mandatory">bool type true if mandatory</param>
        /// <param name="isReadOnly">bool type true if readonly</param>
        /// <param name="isUpdateable">bool type true if updateable</param>
        public VTextBoxButton(string columnName, bool mandatory, bool isReadOnly, bool isUpdateable, int dislaytype, Lookup lookup)
        {
            InitializeComponent();

            SetParameter(columnName, mandatory, isReadOnly, isUpdateable, dislaytype, lookup, null);

            //log = Logging.VLogger.GetVLogger(typeof(VTextBoxButton).FullName);

            //_columnName = columnName;
            //_lookup = lookup;
            //this.Name = columnName;
            ////m_mLocation = mLocation;
            //_displayType = dislaytype;
            //_mandatory = mandatory;
            //_readOnly = isReadOnly;
            ////txtText.ReadOnly = true;

            ////	Editable
            //if (isReadOnly || !isUpdateable)
            //{
            //    this.SetReadOnly(true);
            //}
            //else
            //{
            //    this.SetReadOnly(false);
            //}
            ////this.Width = 200;
            //SetPicButton(dislaytype);

            //if (!DataBase.GlobalVariable.IsVisualEditor)
            //{
            //    this.txtText.TextChanged += new System.EventHandler(this.txtText_TextChanged);
            //    this.txtText.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtText_KeyDown);
            //    this.txtText.Leave += new System.EventHandler(this.txtText_Leave);
            //    this.txtText.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtText_KeyUp);
            //    this.imgBtn1.Click += new System.EventHandler(this.imgBtn1_Click);
            //    this.ibtnImage.Click += new System.EventHandler(this.ibtnImage_Click);

            //    SetPopUp();
            //}
            //else
            //{
            //    this.txtText.MouseDown += new MouseEventHandler(txtText_MouseDown);
            //    this.txtText.MouseMove += new MouseEventHandler(txtText_MouseMove);
            //    this.txtText.MouseUp += new MouseEventHandler(txtText_MouseUp);
            //}
            //this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;

            //SetControl UI
        }

        public void SetParameter(string columnName, bool mandatory, bool isReadOnly, bool isUpdateable, int dislaytype, Lookup lookup, int? windowNumber)
        {
            //InitializeComponent();
            if (log == null)
            {
                log = Logging.VLogger.GetVLogger(typeof(VTextBoxButton).FullName);
            }

            if (windowNumber != null)
            {
                _windowNum = windowNumber.Value;
            }

            _columnName = columnName;
            _lookup = lookup;
            //this.Name = columnName;
            //m_mLocation = mLocation;
            _displayType = dislaytype;
            _mandatory = mandatory;
            _readOnly = isReadOnly;
            //txtText.ReadOnly = true;

            //	Editable
            if (isReadOnly || !isUpdateable)
            {
                this.SetReadOnly(true);
            }
            else
            {
                this.SetReadOnly(false);
            }
            //this.Width = 200;
            SetPicButton(dislaytype);

            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                this.txtText.TextChanged += OnTextChanged;
                this.txtText.KeyDown += new KeyEventHandler(txtText_KeyDown);
                this.txtText.KeyUp += new KeyEventHandler(txtText_KeyUp);
                // this.imgBtn1.Click += new System.EventHandler(this.imgBtn1_Click);
                //this.ibtnImage.Click += new System.EventHandler(this.ibtnImage_Click);

                SetPopUp();
            }
            else
            {
                //this.txtText.MouseDown += new MouseEventHandler(txtText_MouseDown);
                //this.txtText.MouseMove += new MouseEventHandler(txtText_MouseMove);
                //this.txtText.MouseUp += new MouseEventHandler(txtText_MouseUp);
                //this.txtText.MouseEnter += new EventHandler(txtText_MouseEnter);
            }
            // this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;

            //txtValue.TextChanged += OnValueChanghed;
            txtText.TextChanged += OnTextChanged;

            btnLink.Click += imgBtn1_Click;

            btn.Click += ibtnImage_Click;
        }

        public VTextBoxButton(string columnName, bool mandatory, bool isReadOnly, bool isUpdateable, int dislaytype, Lookup lookup, int windowNumber)
        {
            InitializeComponent();

            SetParameter(columnName, mandatory, isReadOnly, isUpdateable, dislaytype, lookup, windowNumber);

            //_columnName = columnName;
            //_lookup = lookup;
            //this.Name = columnName;
            ////m_mLocation = mLocation;
            //_displayType = dislaytype;
            //_mandatory = mandatory;
            //_readOnly = isReadOnly;
            ////txtText.ReadOnly = true;
            //_windowNum = windowNumber;
            ////	Editable
            //if (isReadOnly || !isUpdateable)
            //{
            //    this.SetReadOnly(true);
            //}
            //else
            //{
            //    this.SetReadOnly(false);
            //}
            ////this.Width = 200;
            //SetPicButton(dislaytype);

            //SetPopUp();

            //this.txtText.TextChanged += new System.EventHandler(this.txtText_TextChanged);
            //this.txtText.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtText_KeyDown);
            //this.txtText.Leave += new System.EventHandler(this.txtText_Leave);
            //this.txtText.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtText_KeyUp);
            //this.imgBtn1.Click += new System.EventHandler(this.imgBtn1_Click);
            //this.ibtnImage.Click += new System.EventHandler(this.ibtnImage_Click);

            //SetControl UI
        }

        /// <summary>
        /// Set Pic of Buttons
        /// </summary>
        /// <param name="displayType"></param>
        private void SetPicButton(int displayType)
        {
            //txtText.Width += imgBtn1.Width;
            //imgBtn.Width = 0;
            ///imgBtn1.Enabled = true;
            //btnImage.Enabled = true;

            if (displayType == DisplayType.Location)
            {

                imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("Location10.png");
                if (_readOnly)
                {
                    //imgBtn1.Enabled = false;
                    //ibtnImage.Enabled = false;
                }
                txtText.IsReadOnly = true;
            }
            else if (displayType == DisplayType.Locator)
            {
                _locator = (MLocatorLookup)_lookup;

                imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("Locator10.png");

                if (_readOnly)
                {
                    //ibtnImage.Enabled = false;
                }
            }
            //else if (displayType == DisplayType.Account)
            //{
            //    imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("Account10.png");
            //    if (_readOnly)
            //    {
            //        //ibtnImage.Enabled = false;
            //    }
            //}
            //else if (displayType == DisplayType.PAttribute)
            //{
            //    imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("PAttribute10.png");
            //    if (_readOnly)
            //    {
            //        //ibtnImage.Enabled = false;
            //    }
            //}

            else if (displayType == DisplayType.Search)
            {
                if (_columnName.Equals("C_BPartner_ID")
                || (_columnName.Equals("C_BPartner_To_ID") && _lookup.GetColumnName().Equals("C_BPartner.C_BPartner_ID")))
                {
                    imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("BPartner10.png");
                }
                else if (_columnName.Equals("M_Product_ID")
                || (_columnName.Equals("M_Product_To_ID") && _lookup.GetColumnName().Equals("M_Product.M_Product_ID")))
                {
                    imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("Product10.png");
                }
                else
                {
                    imgBtn.Source = VAdvantage.Utility.Envs.LoadImageSource("PickOpen10.png");
                }
                if (_readOnly)
                {
                    //ibtnImage.Enabled = false;
                }
            }
        }

        /// <summary>
        /// create and add menu items in pop up
        /// </summary>
        private void SetPopUp()
        {
            //this.txtText.ContextMenuStrip = popupMenu;
            popupMenu = new ContextMenuStrip();
            popupMenu.AddMenuListener(this);

            if (DisplayType.Search == _displayType || _displayType == DisplayType.Locator)
            {
                popupMenu.AddZoomItem();

                SetZoomButton();

                popupMenu.AddRequeryItem();


                //	VBPartner quick entry link
                if (_columnName.Equals("C_BPartner_ID") && DisplayType.Search == _displayType)
                {
                    popupMenu.AddNewItem();
                    popupMenu.AddUpdateItem();
                }
                if (_lookup != null && _displayType != DisplayType.Locator)
                {
                    if (_lookup.GetZoomWindow() == 0 && (_field == null || _field.GetZoomWindow_ID() < 1))
                    {
                        popupMenu.ZoomItem.IsEnabled = false;
                        zoomButton.IsEnabled = false;
                    }
                }
            }
            else if (DisplayType.Location == _displayType)
            {
                popupMenu = new ContextMenuStrip();
                popupMenu.AddDeleteItem();
            }

            if (popupMenu != null)
            {
                //Listner for contextmenu item 's click event
                popupMenu.AddContextListener(this);
                ContextMenuService.SetContextMenu(this, popupMenu);
            }
        }

        private void SetZoomButton()
        {
            zoomButton = Envs.GetZoomButton();
            zoomButton.Click += new RoutedEventHandler(zoomButton_Click);
        }

        void zoomButton_Click(object sender, RoutedEventArgs e)
        {

            ZoomActionSearch();
            //throw new NotImplementedException();
        }

        internal Button GetzoomButton()
        {
            return zoomButton;
        }

        #region Properties & Functions

        /// <summary>
        /// Text of control
        /// </summary>
        public string Text
        {
            get
            {
                return txtText.Text.Trim();
            }
            set
            {
                try
                {
                    //txtText.Text = "";
                    txtText.Text = value.ToString();
                }
                catch (Exception e)
                {
                    txtText.Text = "";
                }
            }
        }

        /// <summary>
        /// Value Of Control
        /// </summary>
        public Object Value
        {
            get
            {
                return _value;
            }
            set
            {

                _value = value;
            }
        }

        /// <summary>
        /// proerty bind to binding source (single layout)
        /// </summary>
        public void SetGetValue(object value, bool fire)
        {
            if (Util.IsEqual(value, _value))
            {
                return;
            }

            if (value != null && value.ToString() == "")
            {

                return;
            }

            if (DisplayType.Locator == _displayType)
            {
                if (value != null && value != DBNull.Value)
                {
                    _locator.SetOnly_Warehouse_ID(GetOnly_Warehouse_ID());
                    _locator.SetOnly_Product_ID(GetOnly_Product_ID());
                    if (!_locator.IsValid(value))
                        value = null;
                }
            }
            _value = value;
            if (fire)
            {
                _settingText = true;
                txtText.Text = "";
                _settingText = false;
            }
            _settingText = !fire; // fired text chaghed event
            if (!Util.IsNUll(_value))
            {
                //this.txtText.Text = GetText(_value);
                GetText(_value);
                // oldText = this.txtText.Text;
            }
            else
            {
                this.txtText.Text = "";
                oldText = this.txtText.Text;
                _locationValue = null;

            }
            SetColor();
            FireVetoableChangedEvent();
            _settingText = false;

        }


        /// <summary>
        /// new functions
        /// </summary>
        /// <param name="value"></param>
        /// <param name="fire"></param>
        public void SetGetValueNew(object value, bool fire)
        {
            if (Util.IsEqual(value, _value))
            {
                return;
            }

            if (value != null && value.ToString() == "0")
            {
                return;
            }

            if (DisplayType.Locator == _displayType)
            {
                if (value != null && value != DBNull.Value)
                {
                    _locator.SetOnly_Warehouse_ID(GetOnly_Warehouse_ID());
                    _locator.SetOnly_Product_ID(GetOnly_Product_ID());
                    if (!_locator.IsValid(value))
                        value = null;
                }
            }
            _value = value;
            if (fire)
            {
                _settingText = true;
                txtText.Text = "";
                _settingText = false;
            }
            _settingText = !fire; // fired text chaghed event
            if (!Util.IsNUll(_value))
            {
                //this.txtText.Text = GetText(_value);
                GetTextNew(_value);
                // oldText = this.txtText.Text;
            }
            else
            {
                this.txtText.Text = "";
                oldText = this.txtText.Text;
                _locationValue = null;
                SetColor();
            }
            FireVetoableChangedEvent();
            _settingText = false;
        }

        /// <summary>
        /// Get Text Of against ID
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public void GetText(object Id)
        {
            if (worker != null && worker.IsBusy)
            {
                worker.CancelAsync();
                //worker = null;
            }

            //worker = new BackgroundWorker();
            //worker.WorkerSupportsCancellation = true;


            // worker.DoWork += (sender, e) =>
            //  {

            // if (worker.CancellationPending)
            // {
            //     e.Cancel = true;
            // }
            string result = Id.ToString();

            if (_lookup == null)
            {
                this.Text = result;
                return;
            }
            if (_displayType == DisplayType.Location)
            {
                if (Id != null && Id.ToString() != "0" && Id.ToString() != "")
                {
                    result = ((MLocationLookup)_lookup).GetDisplayFromList(Id);
                    if (result == null || result.StartsWith("<"))
                    {
                        ThreadPool.QueueUserWorkItem(delegate
                            {
                                result = ((MLocationLookup)_lookup).GetDisplay(Id);
                                Dispatcher.BeginInvoke(() => this.Text = result);
                            });
                    }
                    else
                    {
                        this.Text = result;
                    }
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        _locationValue = ((MLocationLookup)_lookup).GetLocation(Convert.ToInt32(Id), null);
                    });
                    //string sqlQry = "select ADDRESS1+','+ADDRESS2+','+ADDRESS3+','+ADDRESS4+','+(select Name from C_COUNTRY where C_COUNTRY_ID=cin.C_COUNTRY_ID)+','+(select Name from C_REGION where C_REGION_ID=cin.C_REGION_ID)+','+CITY+','+POSTAL as Location from c_location  cin where cin.c_location_id=" + Id.ToString();
                    //return sqlexec.ExecuteQuery.ExecuteScalar(sqlQry);
                }
                else
                {
                    _locationValue = null;
                    this.Text = "";
                }
            }
            else if (_displayType == DisplayType.Locator)
            {
                if (Id != null && Id.ToString() != "0" && Id.ToString() != "")
                {
                    this.Text = _locator.GetDisplayFromList(Id);
                }
                else
                {
                    this.Text = "";
                }
            }
            else if (_displayType == DisplayType.Search || _field.IsParentColumn())
            {
                string text = _lookup.GetDisplayFromList(Id);

                if (text.StartsWith("<") && text.EndsWith(">"))
                {

                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        text = _lookup.GetDisplay(Id);
                        Dispatcher.BeginInvoke(() => this.Text = text);
                    });
                }
                else
                {
                    this.Text = text;
                }
            }

            else
            {
                this.Text = "";
            }


            // };

            //worker.RunWorkerCompleted += (sender, e) =>
            //    {
            //if (!e.Cancelled && !worker.CancellationPending)
            // {
            // this.txtText.Text = (string)e.Result;
            // oldText = this.txtText.Text;
            // }
            //_settingText = false;
            //worker = null;
            // };
            //worker.RunWorkerAsync();
        }

        /// <summary>
        /// Get Text Of against ID
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public void GetTextNew(object Id)
        {
            if (worker != null && worker.IsBusy)
            {
                worker.CancelAsync();
                //worker = null;
            }
            string result = Id.ToString();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                if (_displayType == DisplayType.Location)
                {
                    if (Id != null && Id.ToString() != "0" && Id.ToString() != "")
                    {
                        result = ((MLocationLookup)_lookup).GetDisplay(Id);

                        _locationValue = ((MLocationLookup)_lookup).GetLocation(Convert.ToInt32(Id), null);

                        //resone to avoid to go in primary thread
                        //if (result == null)
                        //    this.Text = "<" + Id.ToString() + ">";
                        //else
                        //    this.Text = result;
                    }
                    else
                    {
                        _locationValue = null;
                        //this.Text = "";
                        result = "";
                    }
                }
                else if (_displayType == DisplayType.Locator)
                {
                    if (Id != null && Id.ToString() != "0" && Id.ToString() != "")
                    {
                        result = _locator.GetDisplay(Id);
                    }
                    else
                    {
                        result = "";
                    }
                }
                else if (_displayType == DisplayType.Search || _field.IsParentColumn())
                {
                    //this.Text = _lookup.GetDisplayFromList(Id);

                    //Add by raghu 23-Dec-2010
                    result = _lookup.GetDisplay(Id);
                }

                else
                {
                    result = "";
                }
                Dispatcher.BeginInvoke(() => this.Text = result);
            });


            // };

            //worker.RunWorkerCompleted += (sender, e) =>
            //    {
            //if (!e.Cancelled && !worker.CancellationPending)
            // {
            // this.txtText.Text = (string)e.Result;
            // oldText = this.txtText.Text;
            // }
            //_settingText = false;
            //worker = null;
            // };
            //worker.RunWorkerAsync();
        }

        #endregion

        /// <summary>
        /// Click Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ibtnImage_Click(object sender, EventArgs e)
        {
            txtText.Focus();



            //opens Address Window
            if (_displayType == DisplayType.Location)
            {
                OpenLocationForm();
            }
            else if (_displayType == DisplayType.Locator)
            {
                //	Warehouse/Product
                int only_Warehouse_ID = GetOnly_Warehouse_ID();
                int only_Product_ID = GetOnly_Product_ID();

                //    Logging.VLogger.Get().Config("Only Warehouse_ID=" + only_Warehouse_ID
                //+ ", Product_ID=" + only_Product_ID);

                ShowLocatorForm(only_Warehouse_ID, only_Product_ID);
            }
            else if (_displayType == DisplayType.Account)
            {
                //
            }
            else if (_displayType == DisplayType.PAttribute)
            {
                //
            }

            else if (_displayType == DisplayType.Search)
            {
                if (_lookup != null || _field.GetLookup() != null)
                {
                    OpenSearchForm("");
                }
            }
        }

        /// <summary>
        /// Return 0 if null
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private bool IsNULL(object value)
        {
            return value == null || value == DBNull.Value || value.ToString() == "";
        }

        #region Open location Form
        /// <summary>
        /// Open LOcation Column
        /// </summary>
        /// 
        private void OpenLocationForm()
        {
            //this.ParentForm.Cursor = Cursors.WaitCursor;
            //log.Config("" + m_value);

            this.Cursor = Cursors.Wait;

            Framework.EnterNewLocationORAddress frm = new VAdvantage.Framework.EnterNewLocationORAddress(Msg.GetMsg(VAdvantage.Utility.Envs.GetContext(), "Location"), _locationValue);
            frm.Closed += (sender, e) =>
                {
                    _locationValue = frm.GetValue();
                    if (!frm.IsChanged())
                        return;
                    try
                    {
                        int C_Location_ID = 0;
                        if (_locationValue != null)
                            C_Location_ID = _locationValue.GetC_Location_ID();
                        int ii = C_Location_ID;
                        _settingText = true;
                        _focus = true;
                        txtText.Text = "";
                        _value = DBNull.Value;
                        _settingText = false;
                        //txtText.Text = _locationValue.ToString();

                        //ADD IN Locaton :ist SL 
                        MLookupStore.LocOfClientOrgCache[C_Location_ID] = _locationValue.ToString();
                        //End


                        if (EditingControlDataGridView != null)
                        {
                            _value = ii;
                            EditingControlDataGridView.RaiseCellValueChanged(this);
                            _field.SetValue(ii);
                            ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), ii);

                        }
                        else
                        {

                            SetGetValue(ii, true);
                        }
                        _focus = false;
                    }
                    catch (Exception ex)
                    {
                        log.Log(Logging.Level.SEVERE, "", ex);
                    }

                };

            this.Cursor = Cursors.Arrow;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        private void SetNewValue(int id)
        {
            //if (this.Value.ToString() != id.ToString() && this.EditingControlDataGridView != null)
            //{
            //    EditingControlValueChanged = true;
            //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
            //    EditingControlDataGridView.CurrentCell.Value = id;
            //}
            this.Value = id;
        }





        #endregion

        #region "Icontrol Functions


        /// Get Display Type
        /// </summary>
        /// <returns>int</returns>
        public int GetDisplayType()
        {
            return _displayType;
        }

        /// <summary>
        /// Set Display Type
        /// </summary>
        /// <param name="displayType">int display type</param>
        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }



        /// <summary>
        /// Gets Value as LocationID of the control
        /// </summary>
        /// <returns></returns>
        public object GetValue()
        {
            if (_field != null)
            {
                if (this._value == null)
                {
                    return DBNull.Value;
                }
                return this._value;
            }
            else
            {
                if (this._value == DBNull.Value)
                {
                    this._value = null;
                }
                return this._value;
            }
        }

        public string GetText()
        {
            return txtText.Text;
        }


        /// <summary>
        /// Gets whether control is mandatory
        /// </summary>
        /// <returns>bool type</returns>
        public bool GetIsMandatory()
        {
            return _mandatory;
        }
        /// <summary>
        /// Sets Mandatory
        /// </summary>
        /// <param name="value">bool type value</param>
        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        /// <summary>
        /// Gets whether control is set to readonly
        /// </summary>
        /// <returns>bool type</returns>
        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        /// <summary>
        /// Gets field from Model.GridField class
        /// </summary>
        /// <returns>field</returns>
        public GridField GetField()
        {
            return _field;
        }
        public void SetValue(object value)
        {

            SetGetValueNew(value, true);

            //}
            //  _value = value;

        }

        public void SetValueInDataGridColumn(object value)
        {

            SetGetValue(value, false);
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }


        public void SetName(string name)
        {
            this._columnName = name;
        }
        /// <summary>
        /// Gets Name
        /// </summary>
        /// <returns>string</returns>
        public string GetName()
        {
            return this._columnName;
        }

        public void SetText(string value)
        {
            if (value == "")
            {
                _value = null;
            }
            this.Text = "";

        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get;
            set;
        }

        public void SetEnabled(bool enabled)
        {
            this.IsEnabled = enabled;
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                if (zoomButton != null)
                {
                    zoomButton.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }
            }
        }

        /// <summary>
        /// Sets field
        /// </summary>
        /// <param name="field">field</param>
        public void SetField(GridField field)
        {
            if (field != null)
            {
                _windowNum = field.GetWindowNo();
            }
            _field = field;
            if (_field != null && _displayType == DisplayType.Search && MRole.GetDefault().IsShowPreference())
            {
                Framework.ValuePreference.AddPreferenceMenuItem(null, popupMenu);
            }
        }
        public bool Focused
        {
            get
            {
                return _focus || txtText.Focused || btn.IsFocused;
            }

        }

        /// <summary>
        /// Set ReadOnly
        /// </summary>
        /// <param name="readOnly"></param>
        public void SetReadOnly(bool readOnly)
        {
            this.btn.Visibility = readOnly ? Visibility.Collapsed : Visibility.Visible;
            if (readOnly)
            {
                this.txtText.IsReadOnly = true;
                this.IsTabStop = false;
                //this.txtText.TabStop = false;
            }
            else
            {
                if (_displayType != DisplayType.Location)
                {
                    this.txtText.IsReadOnly = false;
                    this.txtText.IsTabStop = true;
                }
            }

            if (DisplayType.Location == _displayType)
            {
                this.btnLink.Visibility = readOnly ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;

                this.txtText.IsReadOnly = true;
                this.txtText.IsTabStop = false;
                //this.txtText.Width = (ibtnImage.Visible) ? (this.Width - (this.ibtnImage.Width + this.imgBtn1.Width)) : this.Width;

            }
            else
            {
                //this.txtText.Width = (ibtnImage.Visible) ? (this.Width - this.ibtnImage.Width) : this.Width;
            }

            SetBackGround(readOnly);

        }

        //Set BackGround color
        private SolidColorBrush backColorBrush = new SolidColorBrush();

        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.txtText.Background = backColorBrush;
            }
            else
            {
                backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtText.Background = backColorBrush;
                SetColor();
            }

        }

        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.Text == "")
                {
                    backColorBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.txtText.Background = backColorBrush;
                }
                else
                {
                    backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    this.txtText.Background = backColorBrush;
                    if (_field != null)
                        _field.SetError(false);
                }
            }
        }

        #endregion

        /// <summary>
        /// Store multiple Ids (Info)
        /// </summary>
        public Object[] InfoMulipleIds
        {
            get;
            set;

        } /// <summary>

        #region Search

        string _TableName = null;
        string _KeyColumnName = null;
        Info ig = null;
        InfoProduct ip = null;
        InfoBPartner ibp = null;
        bool cancelled = false;

        //Object objResult = null;
        Object[] objResult = null;//Add by Raghu
        public bool multipleSelection = false;//Add by Raghu
        //Raghu
        private static String[] _specialForms = new String[] {
              "ViennaAdvantage.Search."
         };



        /// <summary>
        /// Action on Dropdown
        /// </summary>
        /// <param name="QueryValue">Initial Query Value</param>
        public void OpenSearchForm(string QueryValue)
        {
            if (_textSetting)
            {
                txtText.Text = "";
                txtText.Focus();
                _textSetting = false;
            }

            //Form frame = GetForm(); //get the instance of the new form to be displayed
            ChildWindow frame = GetForm();
            string Col = _lookup.GetColumnName();
            if (Col.IndexOf(".") != -1)
                Col = Col.Substring(Col.IndexOf(".") + 1);

            Context ctx = Envs.GetContext();
            String WhereClause = GetWhereClause(ctx, _columnName, _lookup);
            bool resetValue = false;

            if (Col.Equals("M_Product_ID"))
            {
                //	Reset
                ctx.SetContext(Utility.Envs.WINDOW_INFO, Utility.Envs.TAB_INFO, "M_Product_ID", "0");
                ctx.SetContext(Utility.Envs.WINDOW_INFO, Utility.Envs.TAB_INFO, "M_AttributeSetInstance_ID", "0");
                ctx.SetContext(Utility.Envs.WINDOW_INFO, Utility.Envs.TAB_INFO, "M_Lookup_ID", "0");

                //  Replace Value with name if no value exists
                if (QueryValue.Length == 0 && this.Text.Length > 0)
                {
                    QueryValue = this.Text;   //  Name indicator - otherwise Value
                }
                int M_Warehouse_ID = Utility.Envs.GetContext().GetContextAsInt(_lookup.GetWindowNo(), "M_Warehouse_ID");
                int M_PriceList_ID = Utility.Envs.GetContext().GetContextAsInt(_lookup.GetWindowNo(), "M_PriceList_ID");

                //Add by raghu
                if (_field != null)
                {
                    //int AD_Table_ID = System.Convert.ToInt32(ctx.GetContext(_field.GetWindowNo(), _field.GetTabNo(), "AD_Table_ID"));
                    ////multipleSelection = (MOrderLine.Table_ID ==  AD_Table_ID) || (MInvoiceLine.Table_ID == AD_Table_ID) || (I_PP_Product_BOMLine.Table_ID == AD_Table_ID) || (MProductPrice.Table_ID == AD_Table_ID);
                    //multipleSelection = (MTable.Get_Table_ID("C_OrderLine") == AD_Table_ID) ||
                    //    (MTable.Get_Table_ID("C_InvoiceLine") == AD_Table_ID) ||
                    //    (MTable.Get_Table_ID("M_InOutLine") == AD_Table_ID) ||
                    //    (MTable.Get_Table_ID("M_ProductPrice") == AD_Table_ID);//(I_PP_Product_BOMLine.Table_ID == AD_Table_ID) ||


                    multipleSelection = (ctx.GetContext(_field.GetWindowNo(), _field.GetTabNo(), "KeyColumnName") == "C_OrderLine_ID") ||
                       (ctx.GetContext(_field.GetWindowNo(), _field.GetTabNo(), "KeyColumnName") == "C_InvoiceLine_ID") ||
                       (ctx.GetContext(_field.GetWindowNo(), _field.GetTabNo(), "KeyColumnName") == "M_InOutLine_ID") ||
                       (ctx.GetContext(_field.GetWindowNo(), _field.GetTabNo(), "KeyColumnName") == "M_ProductPrice_ID");
                }

                /* (CR_01)*/
                Type type = GetClass("InfoProduct");
                if (type != null)
                {
                    System.Reflection.ConstructorInfo constructor = null;
                    try
                    {
                        constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(int), typeof(int), typeof(String), typeof(bool), typeof(String) });
                    }
                    catch (Exception e)
                    {
                        log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                    }
                    if (constructor != null)
                    {
                        try
                        {

                            if (Util.GetValueOfInt(Envs.GetCtx().GetContext(_windowNum, Envs.GetCtx().GetContext(_windowNum, 1, "KeyColumnName"))) != 0)
                            {
                                _updating = true;
                            }
                            else
                            {
                                _updating = false;
                            }

                            ig = (Info)constructor.Invoke(new object[] { frame, true, _lookup.GetWindowNo(),
                        M_Warehouse_ID,M_PriceList_ID,QueryValue, multipleSelection, WhereClause});
                            ig.Closed += new EventHandler(ig_Closed);
                            ig.Show();
                            cancelled = ig.IsCancelled();
                            //objResult = obj.GetSelectedKey();
                            objResult = ig.GetSelectedKeys();
                        }
                        catch { }
                    }
                    else
                    {
                        throw new Exception("No Std Constructor");
                    }
                }
                else
                {
                    if (Util.GetValueOfInt(Envs.GetCtx().GetContext(_windowNum, Envs.GetCtx().GetContext(_windowNum, 1, "KeyColumnName"))) != 0)
                    {
                        _updating = true;
                    }
                    else
                    {
                        _updating = false;
                    }

                    ip = new InfoProduct(frame, true, _lookup.GetWindowNo(),
                   M_Warehouse_ID, M_PriceList_ID, QueryValue, multipleSelection, WhereClause);
                    ip.Closed += new EventHandler(ig_Closed);
                    ip.Show();
                    cancelled = ip.IsCancelled();
                    objResult = ip.GetSelectedKeys();
                }
                resetValue = true;
            }
            else if (Col.Equals("C_BPartner_ID"))
            {
                //  Replace Value with name if no value exists
                if (QueryValue.Length == 0 && this.Text.Length > 0)
                    QueryValue = this.Text;
                bool isSOTrx = ctx.IsSOTrx(_lookup.GetWindowNo());

                //ibp = new InfoBPartner(frame, true, _lookup.GetWindowNo(),
                //   QueryValue, isSOTrx, false, WhereClause);

                //Updated by raghu 30thApril,2011
                /***********************************/
                Type type = GetClass("InfoBPartner");
                if (type != null)
                {
                    System.Reflection.ConstructorInfo constructor = null;
                    try
                    {
                        constructor = type.GetConstructor(new Type[] { typeof(Form), typeof(bool), typeof(int), typeof(String), typeof(bool), typeof(bool), typeof(String) });
                    }
                    catch (Exception e)
                    {
                        log.Warning("No transaction Constructor for " + type.FullName + " (" + e.ToString() + ")");
                    }
                    if (constructor != null)
                    {
                        try
                        {
                            ig = (Info)constructor.Invoke(new object[] { frame, true, _lookup.GetWindowNo(),
                        QueryValue, isSOTrx, false, WhereClause});
                            ig.Closed += new EventHandler(ig_Closed);
                            ig.Show();
                            cancelled = ig.IsCancelled();
                            objResult = ig.GetSelectedKeys();
                        }
                        catch { }
                    }
                    else
                    {
                        throw new Exception("No Std Constructor");
                    }
                }
                else
                {
                    ibp = new InfoBPartner(frame, true, _lookup.GetWindowNo(),
                       QueryValue, isSOTrx, false, WhereClause);
                    ibp.Closed += new EventHandler(ig_Closed);
                    ibp.Show();
                    cancelled = ibp.IsCancelled();
                    objResult = ibp.GetSelectedKeys();
                }
                /***********************************/
            }
            else
            {
                if (_TableName == null)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
           {
               GetDirectAccessSQL("*");
               System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(frame, QueryValue, WhereClause));
           });
                }
                else
                {
                    ig = Info.Create(frame, true, _lookup.GetWindowNo(), _TableName, _columnName, QueryValue, false, WhereClause);
                    if (ig == null)
                    {
                        return;
                    }
                    ig.Closed += new EventHandler(ig_Closed);
                    ig.Show();

                    objResult = ig.GetSelectedKeys();
                    cancelled = ig.IsCancelled();
                }
            }

            if (!cancelled && objResult != null)
            {
                //_lookup = (MLookup)_lookup.GetDirect
                //when null value in the control
                if (_value == null)
                {
                    _value = -1;
                }
                if ((_value.ToString() != objResult.ToString()))
                {
                    //_value = 
                    //string str = _lookup.GetDisplay(objResult);
                    //SetTextOfColumn(str);
                    //this.Text = str;
                    //oldText = str;
                    //str = null;
                    SetGetValue(objResult, true);
                    //SetTextOfColumn();
                    // }
                }

                //if (EditingControlDataGridView != null)
                //{
                //    EditingControlValueChanged = true;
                //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
                //    EditingControlDataGridView.CurrentCell.Value = objResult;
                //}

            }
            else //if (cancelled)
            {
                if (IsNULL(_value))
                {
                    _textSetting = false;
                    txtText.Text = "";
                    //txtText_TextChanged(txtText.Text, EventArgs.Empty);
                    //this.OnTextChanged(EventArgs.Empty);
                    //_textSetting = true;
                }
            }
            objResult = null;
        }


        /// <summary>
        /// Get Form From ViennaAdvantage
        /// </summary>
        /// <returns></returns>
        /// <writer>Raghu</writer>
        /// <date>12-Dec-2011</date>
        public Type GetClass(string clazz)
        {
            Type type = null;
            for (int i = 0; i < _specialForms.Length; i++)
            {
                System.Reflection.Assembly asm = null;
                try
                {
                    asm = System.Reflection.Assembly.Load(GlobalVariable.PRODUCT_NAME);
                    type = asm.GetType(_specialForms[i] + clazz);
                }
                catch
                {
                    //type = Type.GetType("VAdvantage.AForm.InfoBPartner");
                }
                if (type == null)
                {
                    type = Type.GetType(_specialForms[i] + clazz);
                }
                //type = asm.GetType(_specialForms[i]);
                //return type;
            }
            return type;
        }


        private void InvoKFunction(ChildWindow frame, string QueryValue, string WhereClause)
        {
            ig = Info.Create(frame, true, _lookup.GetWindowNo(), _TableName, _columnName, QueryValue, false, WhereClause);
            if (ig == null)
            {
                return;
            }
            ig.Closed += new EventHandler(ig_Closed);
            ig.Show();

            objResult = ig.GetSelectedKeys();
            cancelled = ig.IsCancelled();
        }

        void ig_Closed(object sender, EventArgs e)
        {
            this.Focus();
            txtText.Focus();
            _focus = true;

            bool forceReset = false;
            if (ig != null)
            {
                objResult = ig.GetSelectedKeys();
                cancelled = ig.IsCancelled();
                forceReset = ig.GetForceResetValue();
                ig.Closed -= new EventHandler(ig_Closed);
            }
            else if (ip != null)
            {
                objResult = ip.GetSelectedKeys();
                cancelled = ip.IsCancelled();
                forceReset = ip.GetForceResetValue();
                ip.Closed -= new EventHandler(ig_Closed);
            }
            else if (ibp != null)
            {
                objResult = ibp.GetSelectedKeys();
                cancelled = ibp.IsCancelled();
                forceReset = ibp.GetForceResetValue();
                ibp.Closed -= new EventHandler(ig_Closed);
            }

            if (!cancelled && objResult != null)
            {

                //when null value in the control
                if (_value == null)
                {
                    _value = -1;
                }

                /*Change Request (CR_02)*/
                /* perform Callout */
                if (forceReset)
                {
                    _value = -1;
                    _field.SetValue(_value);
                }

                if (objResult != null && objResult.Length == 1 && _value.ToString().Equals(objResult.GetValue(0).ToString()))
                {
                    ;
                }

                else
                {
                    //if ((_value.ToString() != objResult.ToString()))
                    InfoMulipleIds = null;

                    if (objResult != null && objResult.Length == 1)
                    {
                        //multipleSelection = false;
                    }

                    if (EditingControlDataGridView != null)
                    {
                        //if (objResult.Length > 1)
                        //{

                        //    object[] ids = new Object[objResult.Length - 1];
                        //    Array.Copy(objResult, 1, ids, 0, ids.Length);
                        //    InfoMulipleIds = ids;
                        //}

                        _value = objResult[0];
                        EditingControlDataGridView.RaiseCellValueChanged(this);
                        _field.SetValue(objResult[0]);
                        ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), objResult.GetValue(0));

                    }
                    else
                    {

                        if (objResult.Length > 1)
                        {

                            object[] ids = new Object[objResult.Length - 1];
                            Array.Copy(objResult, 1, ids, 0, ids.Length);
                            InfoMulipleIds = ids;
                        }

                        SetGetValue(objResult[0], true);
                    }
                    //SetGetValue(objResult, true);
                }
            }
        }

        /// <summary>
        /// Get Where Clause
        /// </summary>
        /// <param name="ctx">Current Context</param>
        /// <param name="_ColumnName">Column Name</param>
        /// <param name="_Lookup">Lookup reference</param>
        /// <returns>where clause or ""</returns>
        public static String GetWhereClause(Context ctx, String _ColumnName, Lookup _Lookup)
        {
            //_Lookup = (MLookup)_Lookup;
            String WhereClause = "";
            try
            {

                if (((MLookup)_Lookup) == null)
                    return "";
                if (((MLookup)_Lookup).GetZoomQuery() != null)
                    WhereClause = ((MLookup)_Lookup).GetZoomQuery().GetWhereClause();
                String validation = ((MLookup)_Lookup).GetValidation();
                if (validation == null)
                    validation = "";
                if (WhereClause.Length == 0)
                    WhereClause = validation;
                else if (validation.Length > 0)
                    WhereClause += " AND " + validation;
                //	//log.finest("ZoomQuery=" + (_lookup.getZoomQuery()==null ? "" : _lookup.getZoomQuery().getWhereClause())
                //		+ ", Validation=" + _lookup.getValidation());
                if (WhereClause.IndexOf('@') != -1)
                {
                    String validated = Envs.ParseContext(ctx, _Lookup.GetWindowNo(), WhereClause, false);
                    if (validated.Length == 0)
                    {
                        ////log.severe(_columnName + " - Cannot Parse=" + whereClause);
                    }
                    else
                    {
                        ////log.fine(_columnName + " - Parsed: " + validated);
                        return validated;
                    }
                }
            }
            catch
            {
            }
            return WhereClause;
        }

        /// <summary>
        /// Gets the new instance of the window form
        /// </summary>
        /// <returns>Object form</returns>
        //public Form GetForm()
        //{
        //    Form frm = new Form();
        //    return frm;
        //}
        public ChildWindow GetForm()
        {
            ChildWindow frm = new ChildWindow();
            return frm;
        }
        // WindowNo for Find           */
        public const int WINDOW_FIND = 1110;

        // WinowNo for MLookup         */
        public const int WINDOW_MLOOKUP = 1111;

        // WindowNo for PrintCustomize */
        public const int WINDOW_CUSTOMIZE = 1112;

        // WindowNo for PrintCustomize */
        public const int WINDOW_INFO = 1113;

        // Tab for Info                */
        public const int TAB_INFO = 1113;

        // WindowNo for AccountEditor */
        public const int WINDOW_ACCOUNT = 1114;

        /// <summary>
        /// event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void preferenceItem_Click(object sender, EventArgs e)
        {
            if (MRole.GetDefault().IsShowPreference())
            {
                // opens Value preference window
                //Framework.ValuePreference obj = Framework.ValuePreference.Start(_field, GetValue(), GetText());
                //if (obj != null)
                //{
                //    obj.ShowDialog();
                //}
            }
            return;
        }

        /// <summary>
        /// Generate Access SQL for Search.
        /// The SQL returns the ID of the value entered
        /// Also sets _tableName and _keyColumnName
        /// </summary>
        /// <param name="text">uppercase text for LIKE comparison</param>
        /// <returns>sql or ""</returns>
        private String GetDirectAccessSQL(String text)
        {
            String[] result = GetDirectAccessSQL(Envs.GetContext(), _columnName, _lookup, text);
            _TableName = result[1];
            _KeyColumnName = result[2];
            return result[0];
        }

        /// <summary>
        /// Generate Access SQL for Search.
        /// The SQL returns the ID of the value entered
        /// Also sets _tableName and _keyColumnName
        /// </summary>
        /// <param name="ctx">Current Context</param>
        /// <param name="_columnName">Column Name</param>
        /// <param name="_lookup">Lookup Object</param>
        /// <param name="text">uppercase text for LIKE comparison</param>
        /// <returns>An array of 3 Strings; 0=SQL, 1=_tableName, 2=_keyColumnName</returns>
        public static String[] GetDirectAccessSQL(Context ctx, String _columnName, Lookup _lookup, String text)
        {
            StringBuilder sql = new StringBuilder();
            String _tableName = _columnName.Substring(0, _columnName.Length - 3);
            String _keyColumnName = _columnName;
            //
            if (_columnName.Equals("M_Product_ID"))
            {
                //	Reset
                ctx.SetContext(WINDOW_INFO, TAB_INFO, "M_Product_ID", "0");
                ctx.SetContext(WINDOW_INFO, TAB_INFO, "M_AttributeSetInstance_ID", "0");
                ctx.SetContext(WINDOW_INFO, TAB_INFO, "M_Locator_ID", "0");
                //
                sql.Append("SELECT M_Product_ID FROM M_Product WHERE (UPPER(Value) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text))
                    .Append(" OR UPPER(Name) LIKE ").Append(GlobalVariable.TO_STRING(text))
                    .Append(" OR UPC LIKE ").Append(GlobalVariable.TO_STRING(text)).Append(")");
            }
            else if (_columnName.Equals("C_BPartner_ID"))
            {
                sql.Append("SELECT C_BPartner_ID FROM C_BPartner WHERE (UPPER(Value) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text))
                    .Append(" OR UPPER(Name) LIKE ").Append(GlobalVariable.TO_STRING(text)).Append(")");
            }
            else if (_columnName.Equals("C_Order_ID"))
            {
                sql.Append("SELECT C_Order_ID FROM C_Order WHERE UPPER(DocumentNo) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
            }
            else if (_columnName.Equals("C_Invoice_ID"))
            {
                sql.Append("SELECT C_Invoice_ID FROM C_Invoice WHERE UPPER(DocumentNo) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
            }
            else if (_columnName.Equals("M_InOut_ID"))
            {
                sql.Append("SELECT M_InOut_ID FROM M_InOut WHERE UPPER(DocumentNo) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
            }
            else if (_columnName.Equals("C_Payment_ID"))
            {
                sql.Append("SELECT C_Payment_ID FROM C_Payment WHERE UPPER(DocumentNo) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
            }
            else if (_columnName.Equals("GL_JournalBatch_ID"))
            {
                sql.Append("SELECT GL_JournalBatch_ID FROM GL_JournalBatch WHERE UPPER(DocumentNo) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
            }
            else if (_columnName.Equals("SalesRep_ID"))
            {
                sql.Append("SELECT AD_User_ID FROM AD_User WHERE UPPER(Name) LIKE ")
                    .Append(GlobalVariable.TO_STRING(text));
                _tableName = "AD_User";
                _keyColumnName = "AD_User_ID";
            }
            //	Predefined
            if (sql.Length > 0)
            {
                String wc = GetWhereClause(ctx, _columnName, _lookup);
                if (wc != null && wc.Length > 0)
                    sql.Append(" AND ").Append(wc);
                sql.Append(" AND IsActive='Y'");
                //	***
                // //log.finest(_columnName + " (predefined) " + sql.toString());
                return new String[] {
				 MRole.GetDefault().AddAccessSQL( sql.ToString(), _tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO ),
					_tableName, _keyColumnName };
            }

            //	Check if it is a Table Reference
            IDataReader dr = null;
            if (_lookup != null && _lookup.GetType() == typeof(MLookup))
            {
                int AD_Reference_ID = ((MLookup)_lookup).GetAD_Reference_Value_ID();
                if (AD_Reference_ID != 0)
                {
                    String query = "SELECT kc.ColumnName, dc.ColumnName, t.TableName "
                        + "FROM AD_Ref_Table rt"
                        + " INNER JOIN AD_Column kc ON (rt.Column_Key_ID=kc.AD_Column_ID)"
                        + " INNER JOIN AD_Column dc ON (rt.Column_Display_ID=dc.AD_Column_ID)"
                        + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID) "
                        + "WHERE rt.AD_Reference_ID=@refid";
                    String displayColumnName = null;

                    try
                    {
                        SqlParameter[] param = new SqlParameter[1];
                        param[0] = new SqlParameter("@refid", AD_Reference_ID);
                        dr = DataBase.DB.ExecuteReader(query, param);
                        while (dr.Read())
                        {
                            _keyColumnName = dr[0].ToString();
                            displayColumnName = dr[1].ToString();
                            _tableName = dr[2].ToString();
                        }
                        dr.Close();
                        dr = null;

                    }
                    catch (Exception e)
                    {
                        if (dr != null)
                        {
                            dr.Close();
                            dr = null;
                        }
                        Logging.VLogger.Get().Log(Logging.Level.SEVERE, query, e);
                    }

                    if (displayColumnName != null)
                    {
                        sql = new StringBuilder();
                        sql.Append("SELECT ").Append(_keyColumnName)
                            .Append(" FROM ").Append(_tableName)
                            .Append(" WHERE UPPER(").Append(displayColumnName)
                            .Append(") LIKE ").Append(GlobalVariable.TO_STRING(text))
                            .Append(" AND IsActive='Y'");
                        String wc = GetWhereClause(ctx, _columnName, _lookup);
                        if (wc != null && wc.Length > 0)
                            sql.Append(" AND ").Append(wc);
                        //	***
                        //log.finest(_columnName + " (Table) " + sql.toString());
                        return new String[] {
							MRole.GetDefault().AddAccessSQL( sql.ToString(), _tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO ),
							_tableName, _keyColumnName };
                    }
                }	//	Table Reference
            }	//	MLookup

            /** Check Well Known Columns of Table - assumes TableDir	**/
            String squery = "SELECT t.TableName, c.ColumnName "
                + "FROM AD_Column c "
                + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID AND t.IsView='N') "
                + "WHERE (c.ColumnName IN ('DocumentNo', 'Value', 'Name') OR c.IsIdentifier='Y')"
                + " AND c.AD_Reference_ID IN (10,14)"
                + " AND EXISTS (SELECT * FROM AD_Column cc WHERE cc.AD_Table_ID=t.AD_Table_ID"
                    + " AND cc.IsKey='Y' AND cc.ColumnName=@colname)";
            _keyColumnName = _columnName;
            sql = new StringBuilder();

            //IDataReader dr = null;
            try
            {
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@colname", _keyColumnName);
                dr = DataBase.DB.ExecuteReader(squery, param);

                while (dr.Read())
                {
                    if (sql.Length != 0)
                        sql.Append(" OR ");
                    _tableName = dr[0].ToString();
                    sql.Append("UPPER(").Append(dr[1].ToString()).Append(") LIKE ").Append(GlobalVariable.TO_STRING(text));
                }
                dr.Close();
                dr = null;

            }
            catch (Exception ex)
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
                Logging.VLogger.Get().Log(Logging.Level.SEVERE, sql.ToString(), ex);
            }


            if (sql.Length == 0)
            {
                Logging.VLogger.Get().Log(Logging.Level.SEVERE, _columnName + " (TableDir) - no standard/identifier columns");
                return new String[] { "", _tableName, _keyColumnName };
            }
            //
            StringBuilder retValue = new StringBuilder("SELECT ")
                .Append(_columnName).Append(" FROM ").Append(_tableName)
                .Append(" WHERE ").Append(sql)
                .Append(" AND IsActive='Y'");
            String _wc = GetWhereClause(ctx, _columnName, _lookup);
            if (_wc != null && _wc.Length > 0)
                retValue.Append(" AND ").Append(_wc);
            //	***
            ////log.finest(_columnName + " (TableDir) " + sql.toString());
            return new String[] {
				MRole.GetDefault().AddAccessSQL( retValue.ToString(), _tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO ),
				_tableName, _keyColumnName };
        }	//	getDirectAccessSQL

        /// <summary>
        /// Opens window through zoom
        /// </summary>
        /// <param name="lookup">lookup</param>
        /// <param name="zoomQuery">query</param>
        /// <param name="value">selected value</param>
        /// <param name="columnName">column name</param>
        public void ZoomAction(Lookup lookup, Query zoomQuery, Object value, String columnName)
        {
            if (_lookup == null)
                return;
            //	If not already exist or exact value

            if (value == null || value.ToString() == "-1" || value.ToString().Trim() == "")
            {
                value = new KeyNamePair(-1, "");
            }


            this.Cursor = Cursors.Wait;
            if (zoomButton != null)
            {
                zoomButton.IsEnabled = false;
            }

            int AD_Window_ID = 0;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (sender, e) =>
                {
                    if (zoomQuery == null || value != null)
                    {
                        zoomQuery = new Query();	//	ColumnName might be changed in MTab.validateQuery

                        string keyColumnName = null;
                        //	Check if it is a Table Reference
                        if (lookup != null && lookup is MLookup)
                        {
                            // get reference id
                            int AD_Reference_ID = ((MLookup)lookup).GetAD_Reference_Value_ID();
                            if (AD_Reference_ID != 0)
                            {
                                string query = "SELECT kc.ColumnName"
                                    + " FROM AD_Ref_Table rt"
                                    + " INNER JOIN AD_Column kc ON (rt.Column_Key_ID=kc.AD_Column_ID)"
                                    + "WHERE rt.AD_Reference_ID=" + AD_Reference_ID;
                                IDataReader dr = null;
                                try
                                {
                                    dr = DB.ExecuteReader(query);
                                    if (dr.Read())
                                    {
                                        keyColumnName = dr["ColumnName"].ToString();
                                    }
                                    dr.Close();
                                    dr = null;
                                }
                                catch (Exception ex)
                                {
                                    if (dr != null)
                                    {
                                        dr.Close();
                                        dr = null;
                                    }
                                    // fill error log in case of any error occured
                                    //Common.ErrorLog.FillErrorLog("VTextBoxButton.ZoomAction", GlobalVariable.LAST_EXECUTED_QUERY, ex.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                                    log.Log(Logging.Level.SEVERE, ex.Message);
                                }
                            }
                        }
                        // Add where clause in query
                        if (keyColumnName != null && keyColumnName.Length != 0)
                            zoomQuery.AddRestriction(keyColumnName, Query.EQUAL, value);
                        else
                            zoomQuery.AddRestriction(columnName, Query.EQUAL, value);
                        // set record count of query=1
                        zoomQuery.SetRecordCount(1);
                    }
                    // get window id of window to be opened
                    if (_field.GetZoomWindow_ID() > 0)
                    {
                        AD_Window_ID = _field.GetZoomWindow_ID();
                    }
                    else
                    {
                        AD_Window_ID = ((MLookup)lookup).GetZoomWindow(zoomQuery);
                    }
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    // get window id of window to be opened

                    //
                    log.Info(columnName + " - AD_Window_ID=" + AD_Window_ID + " - Query=" + zoomQuery + " - Value=" + value);
                    //

                    Apps.AWindow frame = new Apps.AWindow();
                    // get window
                    //Framework.VForm obj = frame.InitilizeWindow(zoomQuery, false, AD_Window_ID);
                    if (frame.InitWindow(AD_Window_ID, zoomQuery))
                    {
                        // show the window
                        //frame.StartPosition = FormStartPosition.CenterScreen;
                        // frame.Show();
                    }
                    frame = null;
                    this.Cursor = Cursors.Arrow;
                    bgw = null;
                    if (zoomButton != null)
                    {
                        zoomButton.IsEnabled = true;
                    }
                };

            bgw.RunWorkerAsync();
            //zoomStarted = true;
        }

        /// <summary>
        ///Check, if data returns unique entry, otherwise involve Info via Button
        /// </summary>
        public void ActionText()
        {
            String text = this.txtText.Text.Trim();
            ;
            //	Nothing entered
            if (text == null || text.Length == 0 || text.Equals("%"))
            {
                OpenSearchForm(text);
                return;
            }
            text = text.ToUpper();
            log.Info(_columnName + " - " + text);


            int id = -3;
            Object keyId = null;
            IDataReader dr = null;


            ThreadPool.QueueUserWorkItem(delegate
                {
                    string finalSql = Msg.ParseTranslation(VAdvantage.Utility.Envs.GetContext(), GetDirectAccessSQL(text));
                    try
                    {
                        dr = DataBase.DB.ExecuteReader(finalSql);
                        if (dr.Read())
                        {
                            try
                            {
                                keyId = Convert.ToInt32(dr[0]);	//	first
                            }
                            catch
                            {
                                keyId = dr[0];
                            }
                            id = 1;
                            if (dr.Read())
                            {
                                id = -1;			//	only if unique
                                keyId = null;
                            }
                        }
                        dr.Close();
                        dr = null;
                    }
                    catch (Exception e)
                    {
                        if (dr != null)
                            dr.Close();
                        dr = null;
                        log.Log(Logging.Level.SEVERE, e.Message);
                        //Common.ErrorLog.FillErrorLog("VtextBoxButton.ActionButton()", finalSql, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                        id = -2;
                    }
                    //	Try like
                    if (id == -3 && !text.EndsWith("%"))
                    {
                        text += "%";
                        finalSql = Msg.ParseTranslation(VAdvantage.Utility.Envs.GetContext(), GetDirectAccessSQL(text));
                        try
                        {
                            dr = DB.ExecuteReader(finalSql);
                            if (dr.Read())
                            {
                                //id = rs.getInt(1);		//	first
                                try
                                {
                                    keyId = Convert.ToInt32(dr[0]);	//	first
                                }
                                catch
                                {
                                    keyId = dr[0];
                                }
                                id = 1;
                                if (dr.Read())
                                {
                                    keyId = null;
                                    id = -1;			//	only if unique
                                }
                            }
                            dr.Close();
                        }
                        catch (Exception e)
                        {
                            if (dr != null)
                                dr.Close();
                            dr = null;
                            log.Log(Logging.Level.SEVERE, e.Message);
                            //Common.ErrorLog.FillErrorLog("VtextBoxButton.ActionButton()", finalSql, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                            id = -2;
                        }
                    }

                    Dispatcher.BeginInvoke(() =>
                        {

                            //	No (unique) result
                            if (id < 0 && keyId == null)
                            {
                                if (id == -3)
                                    log.Info(_columnName + " - Not Found - " + finalSql);
                                else
                                    log.Info(_columnName + "- Not Unique -" + finalSql);

                                _value = DBNull.Value;	// force re-display
                                OpenSearchForm(txtText.Text);
                                return;
                            }
                            if (_value != null)
                            {
                                if (_value.ToString() == keyId.ToString())
                                {
                                    return;
                                }
                            }


                            _focus = true;
                            this.Focus();
                            log.Info(_columnName + "- Unique ID - " + finalSql);
                            _value = DBNull.Value;     //  forces re-display if value is unchanged but text updated and still unique
                            //enable vetoable event on textchaged
                            this.txtText.Text = "";
                            _textSetting = false;
                            //txtText.Focus();

                            if (EditingControlDataGridView != null)
                            {
                                EditingControlDataGridView.Focus();
                                _value = keyId;
                                EditingControlDataGridView.isCellinEditMode = false;
                                EditingControlDataGridView.RaiseCellValueChanged(this);
                                _field.SetValue(keyId);
                                ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), keyId);

                            }
                            else
                            {
                                SetGetValue(keyId, true); //bind value and text
                            }

                        });
                });
        }

        #endregion

        #region "Locator"

        /// <summary>
        ///Get Warehouse restriction if any.
        /// </summary>
        /// <returns></returns>
        private int GetOnly_Warehouse_ID()
        {
            Context ctx = VAdvantage.Utility.Envs.GetContext();
            // gwu: do not restrict locators by warehouse when in Import Inventory Transactions window 
            String AD_Table_ID = ctx.GetContext(_windowNum, "0|AD_Table_ID", true);
            if ("572".Equals(AD_Table_ID)) // Import Inventory Transactions
            {
                return 0;
            }

            String only_Warehouse = ctx.GetContext(_windowNum, "M_Warehouse_ID", true);
            int only_Warehouse_ID = 0;
            try
            {
                if (only_Warehouse != null && only_Warehouse.Length > 0)
                    only_Warehouse_ID = int.Parse(only_Warehouse);
            }
            catch (Exception ex)
            {
                log.Log(Logging.Level.SEVERE, ex.Message);
            }
            return only_Warehouse_ID;
        }

        /// <summary>
        ///Get Product restriction if any.
        /// </summary>
        /// <returns></returns>
        private int GetOnly_Product_ID()
        {
            //	if (!VAdvantage.Utility.Env.isSOTrx(VAdvantage.Utility.Env.getCtx(), m_WindowNo))
            //		return 0;	//	No product restrictions for PO
            //
            Context ctx = VAdvantage.Utility.Envs.GetContext();
            // gwu: do not restrict locators by product when in Import Inventory Transactions window 
            String AD_Table_ID = ctx.GetContext(_windowNum, "0|AD_Table_ID", true);
            if ("572".Equals(AD_Table_ID)) // Import Inventory Transactions
            {
                return 0;
            }

            String only_Product = ctx.GetContext(_windowNum, "M_Product_ID", true);
            int only_Product_ID = 0;
            try
            {
                if (only_Product != null && only_Product.Length > 0)
                    only_Product_ID = int.Parse(only_Product);
            }
            catch (Exception ex)
            {
                log.Log(Logging.Level.SEVERE, ex.Message);
            }
            return only_Product_ID;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="only_Warehouse_ID"></param>
        /// <param name="only_Product_ID"></param>
        public void ShowLocatorForm(int only_Warehouse_ID, int only_Product_ID)
        {
            //	 Button - Start Dialog
            int M_Locator_ID = 0;
            if (_value is int)
                M_Locator_ID = (int)_value;
            else
            {
                if (_value != null && _value.ToString() != "")
                    M_Locator_ID = int.Parse(_value.ToString());
            }

            _locator.SetOnly_Warehouse_ID(only_Warehouse_ID);
            _locator.SetOnly_Product_ID(only_Product_ID);

            bool isReturnTrx = "Y".Equals(VAdvantage.Utility.Envs.GetContext().GetContext(_windowNum, "IsReturnTrx"));
            bool isSOTrx = VAdvantage.Utility.Envs.GetContext().IsSOTrx(_windowNum);
            bool isOnlyOutgoing = ((isSOTrx && !isReturnTrx) ||
                                      (!isSOTrx && isReturnTrx))
                                      && _columnName.Equals("M_Locator_ID");
            _locator.SetOnly_Outgoing(isOnlyOutgoing);
            //_locator.Refresh();


            Dialogs.VLocatorDialog ld = new VAdvantage.Dialogs.VLocatorDialog(_columnName,
                _locator, M_Locator_ID, _mandatory, only_Warehouse_ID, _windowNum);


            ld.Closed += (s, e) =>
                {
                    bool? ret = ld.DialogResult;

                    if (ret != null && (bool)ret)
                    {

                        if (_value == null || _value.ToString() != ld.GetValue().ToString())
                        {
                            //SetValue(ld.GetValue());
                            //_value = ld.GetValue();
                            //SetTextOfColumn(ld.GetText());

                            if (EditingControlDataGridView != null)
                            {
                                _value = objResult;
                                EditingControlDataGridView.RaiseCellValueChanged(this);
                                _field.SetValue(objResult);
                                ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), objResult);

                            }
                            else
                            {


                                _focus = true;
                                SetGetValue(ld.GetValue(), true);

                                _textSetting = false;
                                _focus = false;

                            }


                            //txtText.Text = ld.GetText();

                            //if (VetoableChangeListener != null)
                            //{
                            //    VetoableChangeListener(this, Event.Empty);

                            //}

                        }


                        else
                        {
                            if (IsNULL(_value))
                            {
                                _textSetting = false;
                                txtText.Text = "";
                                //this.OnTextChanged(EventArgs.Empty);
                                //_textSetting = true;
                            }
                        }
                    }
                };



            ld.Show();


            //if (ld.ShowDialog() == DialogResult.OK)
            //{
            //    //}
            //    //if(ld.IsOkPressed)
            //    //{
            //    if (_value == null || _value.ToString() != ld.GetValue().ToString())
            //    {
            //        //SetValue(ld.GetValue());
            //        _value = ld.GetValue();
            //        SetTextOfColumn(ld.GetText());
            //        _textSetting = false;
            //        txtText.Text = ld.GetText();
            //    }
            //    else
            //    {
            //        if (IsNULL(_value))
            //        {
            //            _textSetting = false;
            //            txtText.Text = "";
            //            //this.OnTextChanged(EventArgs.Empty);
            //            //_textSetting = true;
            //        }
            //    }
            //    _locator.SetOnly_Warehouse_ID(0);
            //}

        }

        /// <summary>
        /// Validates the text field to ensure that it contains a valid locator for the context.
        /// If not valid, the locator dialog is opened.
        /// Note that if the field contains a valid value, the dialog will not open even if
        /// there are duplicate duplicate locators with the same name.
        /// </summary>
        public void ValidateLocatorText()
        {
            //	Warehouse/Product
            int only_Warehouse_ID = GetOnly_Warehouse_ID();
            int only_Product_ID = GetOnly_Product_ID();
            log.Config("Only Warehouse_ID=" + only_Warehouse_ID
                + ", Product_ID=" + only_Product_ID);

            if (!txtText.IsReadOnly &&
                    !ActionText(only_Warehouse_ID, only_Product_ID))
            {
                ShowLocatorForm(only_Warehouse_ID, only_Product_ID);
            }
        }

        /// <summary>
        /// Hit Enter in Text Field
        /// </summary>
        /// <param name="only_Warehouse_ID">if not 0 restrict warehouse</param>
        /// <param name="only_Product_ID">if not 0 restricted product</param>
        /// <returns>true if found</returns>
        private bool ActionText(int only_Warehouse_ID, int only_Product_ID)
        {

            String text = txtText.Text.Trim();
            log.Fine(text);
            //	Null
            if (text == null || text.Length == 0)
            {
                if (_mandatory)
                {
                    return false;
                }
                else
                {
                    SetValue(null);
                    return true;
                }
            }

            _locator.SetOnly_Warehouse_ID(only_Warehouse_ID);
            _locator.SetOnly_Product_ID(only_Product_ID);

            bool IsReturnTrx = "Y".Equals(VAdvantage.Utility.Envs.GetCtx().GetContext(_windowNum, "IsReturnTrx"));
            bool IsSOTrx = VAdvantage.Utility.Envs.GetCtx().IsSOTrx(_windowNum);
            bool isOnlyOutgoing = ((IsSOTrx && !IsReturnTrx) ||
                                      (!IsSOTrx && IsReturnTrx))
                                      && _columnName.Equals("M_Locator_ID");
            _locator.SetOnly_Outgoing(isOnlyOutgoing);

            _locator.Refresh();

            // Perform autocompletion.
            // If multiple hits are found, we'll use the original value in the field
            // if the display text has an exact match (not just the starting charaters)

            int matches = 0;
            int matched_M_Locator_ID = 0;
            int orig_m_value = 0;
            if (_value is int)
                orig_m_value = (int)_value;
            bool matched_orig_m_value = false;

            foreach (KeyNamePair pp in _locator.GetData())
            {
                if (text != null &&
                    pp.GetName().ToUpper().StartsWith(text.ToUpper()))
                {
                    matched_M_Locator_ID = pp.GetKey();

                    // this checks for an exact match with the original value
                    if (pp.GetName().Equals(text) &&
                        orig_m_value == matched_M_Locator_ID)
                        matched_orig_m_value = true;

                    ++matches;
                }
            }

            if (matches == 1) // unique match found
            {
                SetValue(matched_M_Locator_ID);
                return true;
            }
            else if (matches > 1 && matched_orig_m_value) // duplicate matches found
            {
                SetValue(orig_m_value);
                return true;
            }
            return false;
        }

        /// <summary>
        ///	Action - Zoom
        /// </summary>ZoomActionLocator
        private void ZoomActionLocator()
        {
            int AD_Window_ID = 139;				//	hardcoded
            log.Info("");
            //
            //this.ParentForm.Cursor = Cursors.WaitCursor;
            this.Cursor = Cursors.Wait;
            Apps.AWindow frame = new Apps.AWindow();
            if (frame.InitWindow(AD_Window_ID, null))
            {
                //frame.StartPosition = FormStartPosition.CenterScreen;
                // frame.Show();
            }

            //AEnv.showCenterScreen(frame);
            frame = null;
            this.Cursor = Cursors.Arrow;
        }

        #endregion

        #region Function
        private void SetTextOfColumn(string str)
        {
            //if (EditingControlDataGridView != null)
            //{
            //    ((Grids.VTextButtonCell)EditingControlDataGridView.CurrentCell).Text = str;
            //}
        }

        public int Get_ID()
        {
            if (_displayType == DisplayType.Location)
            {
                if (_locationValue == null)
                    return 0;
                return _locationValue.GetC_Location_ID();
            }
            return 0;
        }

        public void SetBackGroundColor(Color clr)
        {
            //this.txtText.BackColor = clr;
        }

        public string GetSelectedText()
        {
            return this.txtText.SelectedText;
        }

        private void imgBtn1_Click(object sender, EventArgs e)
        {
            VAdvantage.Utility.Envs.StartBrowser(VAdvantage.Utility.Envs.GOOGLE_MAPS_URL_PREFIX + _locationValue);
        }

        #endregion

        #region "IContextmenuEvent"
        public void OnMenu(ContextMenuEvent evt)
        {
            if (ContextMenuStrip.REQUERY_EVENT.Equals(evt.GetContextEvent()))
            {
                if (_lookup == null)
                    return;
                _textSetting = true;

                BackgroundWorker bgw = new BackgroundWorker();

                bgw.DoWork += (sd, ed) =>
                    {

                        if (_displayType == DisplayType.Search)
                        {
                            ((MLookup)_lookup).RefreshLookup(_value);
                        }

                        else if (_displayType == DisplayType.Locator)
                        {
                            _locator.Refresh();
                        }
                    };

                bgw.RunWorkerCompleted += (sc, ec) =>
                    {
                        GetText(_value);
                        _textSetting = false;
                    };
                bgw.RunWorkerAsync();

            }
            else if (ContextMenuStrip.ZOOM_EVENT.Equals(evt.GetContextEvent()))
            {
                ZoomActionSearch();
            }
            else if (ContextMenuStrip.NEW_EVENT.Equals(evt.GetContextEvent()))
            {
                ActionBPartner(true);
            }

            else if (ContextMenuStrip.UPDATE_EVENT.Equals(evt.GetContextEvent()))
            {
                ActionBPartner(false);
            }

            else if (ContextMenuStrip.PREFERENCE_EVENT.Equals(evt.GetContextEvent()))
            {
                if (Model.MRole.GetDefault().IsShowPreference())
                {
                    //opens Value preference window
                    Framework.ValuePreference obj = Framework.ValuePreference.Start(_field, GetValue());
                    if (obj != null)
                    {
                        obj.Show();
                    }
                }
                return;
            }
            else if (ContextMenuStrip.DELETE_EVENT.Equals(evt.GetContextEvent()))
            {
                if (!_readOnly)
                {
                    _value = null;
                    _locationLookup = null;
                    _textSetting = true;
                    txtText.Text = "";
                    SetColor();
                    _textSetting = false;
                    OpenLocationForm();
                }
            }
        }

        private void ZoomActionSearch()
        {
            if (_lookup == null)
                return;
            if (_displayType == DisplayType.Search)
            {
                Query zoomQuery = ((MLookup)_lookup).GetZoomQuery();
                // get selected value
                Object value = GetValue();
                ZoomAction(_lookup, zoomQuery, value, _columnName);
            }
            else if (_displayType == DisplayType.Locator)
            {
                ZoomActionLocator();
            }
        }
        #endregion

        private void ActionBPartner(bool newRecord)
        {

            //Dialogs.VBPartner vbp = new Dialogs.VBPartner(_lookup.GetWindowNo());
            int BPartner_ID = 0;
            //  if update, get current value
            if (!newRecord)
            {
                if (_value is int)
                    BPartner_ID = (int)_value;
                else if (_value != null && _value != DBNull.Value)
                    BPartner_ID = int.Parse(_value.ToString());
            }

            Dialogs.VBPartner vbp = new Dialogs.VBPartner(_lookup.GetWindowNo(), BPartner_ID);
            vbp.Show();
            vbp.Closed += (s, e) =>
                {
                    bool? ret = vbp.DialogResult;
                    if (ret != null && (bool)ret)
                    {
                        int result = vbp.GetC_BPartner_ID();

                        if (result == 0					//	0 = not saved
                            && result == BPartner_ID)	//	the same
                            return;
                        //  Maybe new BPartner - put in cache
                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            _lookup.GetDirect(result, false, true);
                        });
                        _focus = true;
                        SetValue(result);
                    }
                    vbp = null;
                };


            // if (vbp.LoadBPartner(BPartner_ID))
            // {
            //     vbp.Show();
            // }
            ////vbp.setVisible(true);
            ////  get result
            //int result = vbp.GetC_BPartner_ID();

            //vbp = null;
            //if (result == 0					//	0 = not saved
            //    && result == BPartner_ID)	//	the same
            //    return;
            ////  Maybe new BPartner - put in cache
            //_lookup.GetDirect(result, false, true);

            //SetValue(result);
            //actionCombo (new Integer(result));      //  data binding

        }

        public void Dispose()
        {
            VetoableChangeListener = null;

            _lookup = null;
            _locator = null;
            _locationLookup = null;
            _locationValue = null;

            if (popupMenu != null)
                popupMenu.Items.Clear();

            popupMenu = null;
            _field = null;
            binding = null;
        }

        public string BindValue
        {
            set
            {
                //this.txtValue.Text = "-11";
                binding = null;
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;

                this.SetBinding(VTextBoxButton.TextValueProperty, binding);

                //this.txtValue.Text = "-11";
            }
        }

        #region "vault"
        /// <summary>
        /// Refresh Text
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshItem_Click(object sender, EventArgs e)
        {
            if (_lookup == null)
                return;
            _textSetting = true;
            if (_displayType == DisplayType.Search)
            {
                //txtText.Text = GetText(_value);
            }
            else if (_displayType == DisplayType.Locator)
            {
                _locator.Refresh();
            }
            _textSetting = false;
        }



        void deleteItem_Click(object sender, EventArgs e)
        {
            if (!_readOnly)
            {
                _value = null;
                _textSetting = true;
                txtText.Text = "";
                SetColor();
                _textSetting = false;
                OpenLocationForm();
            }
        }

        void updateItem_Click(object sender, EventArgs e)
        {
            ActionBPartner(false);
        }

        void newItem_Click(object sender, EventArgs e)
        {
            ActionBPartner(true);
        }



        void txtText_MouseEnter(object sender, EventArgs e)
        {
            // txtText.Cursor = Cursors.SizeAll;
            //this.OnMouseEnter(e);
        }



        void txtText_MouseUp(object sender, MouseEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void txtText_MouseMove(object sender, MouseEventArgs e)
        {
            //throw new NotImplementedException();
            if (_mDown)
            {
                _mDown = false;
                this.OnMouseMove(e);
            }

        }

        private bool _mDown = false;
        void txtText_MouseDown(object sender, MouseEventArgs e)
        {
            _mDown = true;
            //throw new NotImplementedException();
        }
        /// <summary>
        /// textChanged event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void txtText_TextChanged(object sender, System.EventArgs e)
        {
            SetColor();
            //if (!_textSetting && !_settingText)// && !_isNitFireSingle)
            //{
            //    //if (EditingControlDataGridView != null)
            //    //{
            //    //    EditingControlValueChanged = true;
            //    //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
            //    //    EditingControlDataGridView.CurrentCell.Value = GetValue();
            //    //}
            //    if (VetoableChangeListener != null)
            //    {
            //        VetoableChangeListener(this, e);
            //    }

            //}
        }


        private void FireVetoableChangedEvent()
        {
            if (!_textSetting && !_settingText)// && !_isNitFireSingle)
            {
                //if (EditingControlDataGridView != null)
                //{
                //    EditingControlValueChanged = true;
                //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
                //    EditingControlDataGridView.CurrentCell.Value = GetValue();
                //}
                if (VetoableChangeListener != null)
                {
                    VetoableChangeListener(this, EventArgs.Empty);
                }

            }

        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            _focus = true;
            base.OnGotFocus(e);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            _focus = false;
            base.OnLostFocus(e);

            if (_textSetting && _isKeyUpFired)
            {
                if ((_field != null || _lookup != null) && !_readOnly)
                {
                    //Ensure Callout must execute

                    //_field.SetValue(-1, _field.IsInserting());
                    _textSetting = false;
                    if (_displayType == DisplayType.Search)
                    {
                        ActionText();
                    }
                    else if (_displayType == DisplayType.Locator)
                    {
                        ValidateLocatorText();
                    }
                    //if (_textSetting)
                    // {
                    // this.Focus();
                    //txtText.Focus();
                    // }
                }
                _isKeyUpFired = false;
                return;
            }
        }

        //protected override void OnLeave(EventArgs e)
        //{
        //    base.OnLeave(e);
        //    //if (_textSetting && _isKeyUpFired)
        //    //{
        //    //    if ((_field != null || _lookup != null) && !_readOnly)
        //    //    {
        //    //        //Ensure Callout must execute

        //    //        //_field.SetValue(-1, _field.IsInserting());
        //    //        _textSetting = false;
        //    //        if (_displayType == DisplayType.Search)
        //    //        {
        //    //            ActionText();
        //    //        }
        //    //        else if (_displayType == DisplayType.Locator)
        //    //        {
        //    //            ValidateLocatorText();
        //    //        }
        //    //        //if (_textSetting)
        //    //        // {
        //    //        this.Focus();
        //    //        txtText.Focus();
        //    //        // }
        //    //    }
        //    //    _isKeyUpFired = false;
        //        // return;
        //    //}

        //}
        void txtText_Leave(object sender, System.EventArgs e)
        {
            //if (_textSetting)
            //{
            //    if (_field != null && !_readOnly)
            //    {
            //        //Ensure Callout must execute

            //        _field.SetValue(-1, _field.IsInserting());
            //        _textSetting = false;
            //        if (_displayType == DisplayType.Search)
            //        {
            //            ActionText();
            //        }
            //        else if (_displayType == DisplayType.Locator)
            //        {
            //            ValidateLocatorText();
            //        }
            //        //if (_textSetting)
            //       // {
            //            this.Focus();
            //            txtText.Focus();
            //       // }
            //    }
            //    return;
            //}
        }

        /// <summary>
        /// Key down Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private string oldText = "";
        private bool _enterKeyDown = false;

        public void SetEnterKeyDown(bool val)
        {
            _enterKeyDown = val;
        }




        void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            SetColor();
            //if (!_textSetting && !_settingText)// && !_isNitFireSingle)
            //{
            //    //if (EditingControlDataGridView != null)
            //    //{
            //    //    EditingControlValueChanged = true;
            //    //    EditingControlDataGridView.NotifyCurrentCellDirty(true);
            //    //    EditingControlDataGridView.CurrentCell.Value = GetValue();
            //    //}
            //    if (VetoableChangeListener != null)
            //    {
            //        VetoableChangeListener(this, e);
            //    }

            //}

        }


        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
        }

        void txtText_KeyDown(object sender, KeyEventArgs e)
        {
            if (!txtText.IsReadOnly)
            {
                oldText = txtText.Text;
                _textSetting = true;
                _isKeyUpFired = false;
            }
            else
            {
                if (_displayType == DisplayType.Location)
                {
                    if (e.Key == Key.Space)
                    {
                        OpenLocationForm();
                    }
                }
            }
            if (e.Key == Key.Enter)
            {
                _enterKeyDown = true;

            }

            if (e.Key == Key.Tab)
            {
                if (_value == null)
                {
                    _textSetting = true;
                    _isKeyUpFired = true;
                }

            }

        }

        private bool _isKeyUpFired = false;
        private Button zoomButton;
        private void txtText_KeyUp(object sender, KeyEventArgs e)
        {

            if (!txtText.IsReadOnly)
            {
                _isKeyUpFired = true;

                if (e.Key == Key.Delete)
                {
                    _value = null;
                    // _isKeyUpFired = false;
                    //ShowDropDownList();
                }
                else if (e.Key == Key.Back) //BackSpaceKey
                {
                    _value = null;
                    //ShowDropDownList();
                }
                //else
                //{

                if (e.Key == Key.Enter && _enterKeyDown)
                {
                    if ((_field != null || _lookup != null) && !_readOnly)
                    {
                        //_field.SetValue(-1, _field.IsInserting());
                        //_textSetting = false;
                        if (_displayType == DisplayType.Search)
                        {
                            ActionText();
                        }
                        else
                            if (_displayType == DisplayType.Locator)
                            {
                                ValidateLocatorText();
                            }
                    }
                }
                else
                {
                    _textSetting = false;
                    _textSetting = !(oldText == txtText.Text);
                    if (_textSetting)
                    {
                        _value = null;
                    }
                }
                // if (oldText != "")
                // {

                // }

                //}

                base.OnKeyUp(e);
                _enterKeyDown = false;
            }
        }

        #endregion

        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public bool EditingControlFormOpening
        {
            get;
            set;
        }
    }
}
